<?php
class Application_Model_Category implements Zend_Acl_Resource_Interface {
	private $_id;
	private $_name;
	private $_parentId = null;

	public function getId() {
		return $this->_id;
	}

	public function getName() {
		return $this->_name;
	}

	public function getParentId() {
		return $this->_parentId;
	}

	/**
	 * Return parent categories, closest parent as last
	 * @return array
	 */
	public function getParents() {
		if(!$this->_parentId) {
			return array();
		}

		$parents = array();
		$parentId = $this->_parentId;
		while($parentId != null) {
			$category = Application_Model_Category::findById($parentId);
			$parents[] = $category;
			$parentId = $category->getParentId();
		}

		//Need to reverse since we actually put closest in first,
		//so it would be the last in the array
		return array_reverse($parents);
	}

	public function setId($id) {
		$this->_id = $id;
	}

	public function setName($name) {
		$this->_name = $name;
	}

	public function setParentId($id) {
		$this->_parentId = $id;
	}

	public function getAbsoluteUrl() {
		$router = Zend_Controller_Front::getInstance()->getRouter();
		return $router->assemble(array(
			'module'=> 'files',
			'controller' => 'categories',
			'action' => 'list',
			'category' => $this->_id
		));
	}

	public static function findByParentId($id) {
		$db = Zend_Db::factory ( 'Pdo_Mysql', array (
		'host' => 'localhost', 
		'username' => 'root', 
		'password' => '', 
		'dbname' => 'test' )
		 );

		$sql = 'SELECT id, name, parent_id 
                        FROM categories ';
		if(is_null($id)) {
			$sql .= 'WHERE parent_id IS NULL';
		}
		else {
                        $sql .= 'WHERE parent_id = ' . $id;
		}

		$rows = $db->fetchAssoc($sql);

		return self::_hydrateRows($rows);
	}

	public static function findById($id) {
		$db = Zend_Db::factory ( 'Pdo_Mysql', array (
		'host' => 'localhost', 
		'username' => 'root', 
		'password' => '', 
		'dbname' => 'test' )
		 );

		$sql = 'SELECT id, name, parent_id 
                        FROM categories
                        WHERE id = ?';

		$row = $db->fetchRow($sql, array($id), Zend_Db::FETCH_ASSOC);

		$results = self::_hydrateRows(array($row));
		return $results[0];
	}

	private static function _hydrateRows($rows) {
		$results = array();
		foreach($rows as $row) {
			$cat = new Application_Model_Category();
			$cat->setId($row['id']);
			$cat->setName($row['name']);
			$cat->setParentId($row['parent_id']);
			$results[] = $cat;
		}

		return $results;
	}

	public function getResourceId() {
		return 'category-' . $this->_id;
	}
}